package com.imooc.cloud.mall.practice.zuul.filter;

import com.imooc.cloud.mall.practice.common.common.Constant;
import com.imooc.cloud.mall.practice.user.model.pojo.User;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * ClassName: UserFilter
 * Package: com.imooc.cloud.mall.practice.zuul
 *
 * @Author 马学兴
 * @Create 2024/3/6 20:11
 * @Version 1.0
 * Description:用户鉴权过滤器
 */
public class UserFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {//决定是否执行该过滤器，根据请求的 URI 判断是否需要拦截
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String requestURI = request.getRequestURI();
        if (requestURI.contains("images")||requestURI.contains("pay")){// 不拦截请求中包含 "images" 或 "pay" 的 URI
            return false;
        }
        if (requestURI.contains("cart")||requestURI.contains("order")){//拦截
            return true;
        }
        return false;
    }

    @Override
    public Object run() throws ZuulException {//运行过滤器的逻辑，在该方法中进行用户身份验证，若用户未登录，则拦截请求
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        HttpSession session = request.getSession();
        User currentUser =(User) session.getAttribute(Constant.IMOOC_MALL_USER);
        if (currentUser==null){
            currentContext.setSendZuulResponse(false);
            currentContext.setResponseBody("{\\n\" +\n" +
                    "                    \"    \\\"status\\\": 10007,\\n\" +\n" +
                    "                    \"    \\\"msg\\\": \\\"NEED_LOGIN\\\",\\n\" +\n" +
                    "                    \"    \\\"data\\\": null\\n\" +\n" +
                    "                    \"}");
            currentContext.setResponseStatusCode(200);
        }
        return null;
    }
}
